<?php
/**
 * Created by Dumitru Russu
 * User: developer
 * Date: 11/19/12
 * Time: 12:41 PM
 * To change this template use File | Settings | File Templates.
 */
class Db_Locale_ProjectCountriesDeliveryMethodsDays extends Common {
	protected static $tableName = TAB_PROJECT_COUNTRIES_DELIVERY_METHODS_DAYS;
	protected static $dbFields = array(
		'id',
		'pcdy_project_delivery_id',
		'pcdy_day',
		'pcdy_time',
		'pcdy_days_before',
		'pcdy_show_before',
		'pcdy_days_after',
		'pcdy_show_after',
		'pcdy_saturday',
		'deleted'
	);
	/**
	 * @var Db_Locale_ProjectCountriesDeliveryMethodsDays
	 */
	public $objectArray;

	public $id;
	public $pcdy_project_delivery_id;
	public $pcdy_day;
	public $pcdy_time;
	public $pcdy_days_before;
	public $pcdy_show_before;
	public $pcdy_days_after;
	public $pcdy_show_after;
	public $pcdy_saturday;
	public $deleted;

	function __construct($value = null, $fieldName = null) {
		parent::__construct($value, $fieldName);
	}

	public static function getProjectCountriesDeliveryDays($projectCountriesDeliveryMethodId) {
		$deliveryDays = self::findAllByField('pcdy_project_delivery_id', $projectCountriesDeliveryMethodId);
		if(!empty($deliveryDays )) {
			foreach($deliveryDays as $deliveryDay) {
				$deliveryDays['result'][$deliveryDay->pcdy_day] = $deliveryDay;
			}
			return $deliveryDays['result'];
		} else {
			return false;
		}
	}

	public static function deliveryDate($projectCountriesDeliveryMethodId, $daysRestrictions) {
		$tempDate = null;
		$fileName = conf('TEMPORARY_FILE_PUBLIC_HOLIDAYS');
		$holidays = file_get_contents($fileName);
		$holidays = unserialize($holidays);

		if($daysRestrictions == 1) {
			$timeUNIX = time();
			$day = strtolower(date('l', $timeUNIX));

			$dayData = self::$DB->selectRow("SELECT * FROM ?f WHERE deleted = 0
												AND pcdy_day = ? AND pcdy_project_delivery_id = ?", self::$tableName, $day, $projectCountriesDeliveryMethodId);
			$timeData = explode(':', $dayData['pcdy_time']);

			$days = 0;
			$neededTime = mktime($timeData[0], $timeData[1], '00');
			if($timeUNIX < $neededTime) {
				if($dayData['pcdy_show_before'] == 1) {
					$days = $dayData['pcdy_days_before'];
				}
			}
			else {
				if($dayData['pcdy_show_after'] == 1)        {
					$days = $dayData['pcdy_days_after'];
				}
			}

			$deliveryDays = 0;
			while($days != 0) {
				$deliveryDays++;
				$tempDay = date('D', $timeUNIX + 86400 * $deliveryDays);
				$tempDate = date('d.m.Y', $timeUNIX + 86400 * $deliveryDays);
				if($tempDay != 'Sun' && (($tempDay != 'Sat') || ($dayData['pcdy_saturday'] == 1)) && !in_array($tempDate, $holidays)) {
					$days--;
				}
			}

			return $tempDate;
		} else {
			return false;
		}
	}
}
